var locationIds = new Array();
var offsetH = (heightClient)*0.02;
layui.use(['table', 'form'], function () {
    var table = layui.table,
        form = layui.form,
        layDate = layui.laydate;
    var userId = null;
    layDate.render({
        elem: '#validTime'
    });
    table.render(renderTable('#userList', 'user/page', [
        {type: 'numbers', title: '序号'},
        {field: 'loginName', title: '账户', sort: false, align: 'center'},
        {field: 'userName', title: '姓名', sort: false, align: 'center'},
        {field: 'mobilephone', title: '手机号', sort: false, align: 'center'},
        {field: 'roleName', title: '角色', sort: false, align: 'center'},
        {field: 'modifyDate', title: '修改时间', width: '10%', sort: false, align: 'center'},
        {
            field: 'userType', title: '用户类型', sort: false, align: 'center', width: '10%', templet: function (d) {
                if (d['userType'] == 0) return '<span class="layui-badge">系统默认</span>'
                else if (d['userType'] == 1) return '<span class="layui-badge layui-bg-blue">普通用户</span>'
                else return ''
            }
        },
        {
            field: 'valid', title: '状态', sort: false, align: 'center', width: '8%', templet: function (d) {
                if (d.valid == 1) return '<span class="layui-badge layui-bg-green">正常</span>'
                else if (d.valid == 0) return '<span class="layui-badge layui-bg-cyan">禁用</span>'
                else return ''
            }
        },
        {title: '操作', sort: false, align: 'center', toolbar: '#barDemo', width: "32%",fixed: 'right'}
    ]));
    table.on('tool(userList)', function (obj) {
        var data = obj.data;
        userId = data.userId
        if (obj.event === "edit") {
            layer.open({
                type: 1,
                title: "编辑用户信息",
                offset: [offsetH],
                area: ['600px', '540px'],
                content: $("#editFormDiv"),
                success: function () {
                    $("#passwordTr").hide()
                    $("#password").removeAttr("lay-verify")
                    form.val('editForm', {
                        userId: data.userId,
                        loginName: data.loginName,
                        userName: data.userName,
                        mobilephone: data.mobilephone,
                        validDateEnd: data.validDateEnd,
                        email: data.email
                    })
                },
                end: function (i) {
                    layer.close(i)
                    $("#passwordTr").show()
                    $("#password").attr("lay-verify", "pass");
                    hideAndReset("#editFormDiv", "#editForm")
                    userId = null;
                }
            });
        } else if (obj.event === "role") {
            layer.open({
                type: 1,
                title: "角色分配",
                offset: [offsetH],
                area: ['520px', '470px'],
                content: $("#roleDiv"),
                success: function () {
                    getAjaxReq("user/rolesByUserId", {userId: userId}, function (res) {
                        if (res.code == 1) {
                            var roleList = res.data;
                            var roleId = roleList[0].roleId;
                            form.val('roleForm', {
                                'roleId': roleId
                            })
                        }
                    })
                },
                end: function (i) {
                    layer.close(i)
                    hideAndReset("#roleDiv", "#roleForm")
                    userId = null;
                }
            });
        } else if (obj.event === "lock") {
            confirm('确定禁用该用户？', function () {
                postAjaxReq("user/edit",
                    {
                        userId: userId,
                        valid: 0
                    }, function (res) {
                        if (res.code == 1) {
                            table.reload('userList');
                            layer.msg("操作成功")
                        } else {
                            layer.msg(res.msg)
                        }
                        userId = null;
                    })
            })
        } else if (obj.event === "unlock") {
            confirm('确定启用该用户？', function () {
                postAjaxReq("user/edit", {userId: userId, valid: 1}, function (res) {
                    if (res.code == 1) {
                        table.reload('userList');
                        layer.msg("操作成功")
                    } else {
                        layer.msg(res.msg)
                    }
                    userId = null;
                })
            })
        } else if (obj.event === "changePass") {
            layer.open({
                type: 1,
                title: "重置密码",
                offset:['180px'],
                area: ['400px', '220px'],
                content: $("#changePassDiv"),
                end: function (i) {
                    layer.close(i)
                    hideAndReset("#changePassDiv", "#passForm")
                    userId = null;
                }
            });
        } else if (obj.event === "del") {
            confirm('确定要删除该用户？', function () {
                postAjaxReq("user/delete", {userId: userId}, function (res) {
                    if (res.code == 1) {
                        table.reload('userList');
                        layer.msg("删除成功")
                    } else {
                        layer.msg(res.msg)
                    }
                    userId = null;
                })
            })
        } else if (obj.event === "locations") {
            layer.open({
                type: 1,
                title: "数据权限",
                btnAlign: "c",
                offset: [offsetH],
                area: ['600px', '500px'],
                content: $("#locationDiv"),
                success: function () {
                    postAjaxReq("location/listByUserId", {userId: userId},
                        function (result) {
                            if (result.code) {
                                initTree(result.data)
                            }
                        }
                    )
                },
                end: function (i) {
                    $("#locationDiv").hide()
                    layer.close(i)
                    userId = null
                    locationIds = null
                    $("#locationTree").jstree('destroy')
                }
            });
        }
    });
    form.verify({
        pass: [pass, '密码必须6到16位']
    });
    form.on('submit(editSubmit)', function (obj) {
        var url = null;
        var data = obj.field
        if (!isEmpty(userId)) {
            url = "user/edit"
            data.userId = userId
        } else
            url = "user/save"
        if (!isEmpty(data.password))
            data.password = $.md5(data.password)
        postAjaxReq(url, data, function (res) {
            if (res.code == 1) {
                $("#cancel").click();
                layer.msg("操作成功")
                table.reload("userList");
                userId = null;
            } else {
                layer.msg(res.msg)
            }
        })
    });
    $("#search").on("click", function () {
        var keyWord = $("#keyWord").val(),
            valid = $("#valid").val();

        if (valid == -1) valid = null
        table.reload('userList', {
            page: {curr: 1},
            where: {
                keyWord: keyWord,
                valid: valid
            }
        })
    });
    form.on('submit(roleFormSubmit)', function (obj) {
        var data = obj.field
        var reqData = new Array()
        reqData.push({
            roleId: data.roleId,
            userId: userId
        })
        jsonAjaxReq("user/role/save", reqData, function (res) {
            if (res.code == 1) {
                $("#roleCancel").click();
                layer.msg("操作成功")
                table.reload("userList");
                userId = null
            } else {
                layer.msg(res.msg)
            }

        })
    });
    form.on('submit(locationFormSubmit)', function () {
        if (locationIds)
            locationIds.forEach(function (e) {
                e["userId"] = userId
            })
        if (locationIds.length == 0)
            locationIds.push({
                userId: userId
            })

        jsonAjaxReq("user/location/save", locationIds, function (res) {
            if (res.code == 1) {
                $("#locationCancel").click();
                layer.msg("操作成功")
                userId = null
            } else {
                layer.msg(res.msg)
            }
        })
    });
    form.on('submit(passFormSubmit)', function (obj) {
        var data = obj.field
        if (data.password != data.rePassword) {
            return layer.msg("重复密码与密码必须保持一致！", {icon: 0})
        }
        var reqData = {
            password: $.md5(data.password),
            userId: userId
        }
        postAjaxReq("user/edit", reqData, function (res) {
            var msg = res.msg;
            if (res.code == 1) {
                $("#passCancel").click();
                layer.msg("操作成功")
                userId = null
            } else {
                layer.msg(msg)
            }
        })
    });
});
$("#addUser").on("click", function () {
    layer.open({
        type: 1,
        title: "新增用户信息",
        offset: [offsetH],
        area: ['600px', '540px'],
        content: $("#editFormDiv"),
        end: function (i) {
            layer.close(i)
            hideAndReset("#editFormDiv", "#editForm")
        }
    });
});

$("#cancel").on("click", function () {
    hideAndReset("#editFormDiv", "#editForm")
    layer.closeAll()
});

$("#roleCancel").on("click", function () {
    hideAndReset("#roleDiv", "#roleForm")
    layer.closeAll()
});
$("#passCancel").on("click", function () {
    hideAndReset("#changePassDiv", "#passForm")
    layer.closeAll()
});
$("#locationCancel").on("click", function () {
    $("#locationDiv").hide()
    layer.closeAll()
});

function hideAndReset(hide, reset) {
    $(hide).hide()
    $(reset)[0].reset()
}

function initTree(treeList) {
    $('#locationTree').jstree({
        core: {
            data: treeList,
            check_callback: true,
            multiple: true,
            themes: {stripes: true},
            expand_selected_onload: false
        },
        force_text: true,
        plugins: ["wholerow", "checkbox", "types"],
        checkbox: {
            keep_selected_style: false,
            three_state: true
        }
    });
    $('#locationTree').on('changed.jstree', function (e, data) {
        locationIds = new Array();
        data.selected.forEach(function (e) {
            locationIds.push({locationId: e})
        })
    });
}